<template>
  <div>
    <el-dialog title="分配权限" :visible="showDialog" @close="closeFn">
      <!-- check-strictly 父子不相互关联
          :props="{label:'title'}" 指定节点标签为节点对象的某个属性值
          show-checkbox 节点是否可被选择
       -->
      <el-tree ref="tree" :data="permData" show-checkbox default-expand-all node-key="id" :props="{label:'title'}" check-strictly />
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="small" @click="submit">确定</el-button>
          <el-button size="small" @click="closeFn">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { permissionList } from '@/api/permissions'
import { getRoleDetailById, editRole } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permData: [],
      permIds: [],
      currentRoleId: ''
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 权限选择确定按钮
    async submit() {
      this.permIds = this.$refs.tree.getCheckedNodes()
      // console.log(this.permIds)
      // 发送请求
      await editRole({
        id: this.currentRoleId,
        permissions: this.permIds
      })
      // 关闭弹窗
      this.closeFn()
    },
    // 获取角色默认权限数据
    async getRolePermIds(id) {
      // 保存当前角色id
      this.currentRoleId = id
      const res = await getRoleDetailById(id)
      // console.log(res.data.permissions)
      // 获取回来的权限数据的处理
      res.data.permissions.forEach((item) => {
        this.permIds.push(item.id)
      })
      // console.log(this.permIds)
      // 实现回显
      this.$refs.tree.setCheckedKeys(this.permIds)
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:showDialog', false)
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await permissionList()
      // console.log('权限列表', res.data)
      // this.permList = res.data
      // 将数组转换成树形结构
      this.permData = this.listToTree(res.data, '0')
    },
    // 将数组装换为树形结构
    listToTree(arr, id) {
      const list = []
      arr.forEach((item) => {
        if (item.pid === id.toString()) {
          list.push(item)
          // 获取子部门
          item.children = this.listToTree(arr, item.id)
        }
      })
      return list
    }
  }
}
</script>

<style>
</style>
